package com.framework.core.rest;

import com.framework.core.exception.AppException;
import com.framework.core.exception.SystemException;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

/**
 * @author shenmengchao
 * @version 1.0.0
 * @date 2017/7/22
 * @description
 */

public class ItemTypeAdapterFactory implements TypeAdapterFactory {

//    public final static String SUCCESS = "-1";

    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
        final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

        return new TypeAdapter<T>() {

            public void write(JsonWriter out, T value) throws IOException {
                delegate.write(out, value);
            }

            public T read(JsonReader in) throws IOException {

                JsonElement jsonElement = elementAdapter.read(in);
                if (jsonElement.isJsonObject()) {
                    JsonObject jsonObject = jsonElement.getAsJsonObject();
                    if (jsonObject.has("success")) {
                        ItemTypeAdapterFactory.throwExceptionWhenNotSuccess(jsonObject);

                        if (jsonObject.has("result")) {
                            jsonElement = jsonObject.get("result");
                        }
                    }
                }
                return delegate.fromJsonTree(jsonElement);
            }

        }.nullSafe();
    }

    /**
     * 如果有异常，则会抛出异常
     *
     * @param jsonObject
     */
    public static void throwExceptionWhenNotSuccess(JsonObject jsonObject) {

        String success = getJsonValueByKey(jsonObject, "success");
        String code = getJsonValueByKey(jsonObject, "code");
        if (!"true".equals(success)) {
            String message = getJsonValueByKey(jsonObject, "message");
            throw new AppException(code, message);
        }
    }

    private static String getJsonValueByKey(JsonObject jsonObject, String key){
        JsonElement jsonElement = jsonObject.get(key);
        if(null != jsonElement && !jsonElement.isJsonNull()){
            return jsonElement.getAsString();
        }
        return "";
    }
}
